<?php
namespace Zaya\Lib\SSO;

use Throwable;

/**
 * Exception thrown when a request is done while no session is attached
 *
 */
class NotAttachedException extends \Exception
{
    /**
     * The status code to use for the response.
     *
     * @var int
     */
    public static $status = 412;

    /**
     * @var Client|Server
     */
    private $sso;
    /**
     * NotLoginException constructor.
     * @param Server|Client $sso
     * @param string $message
     * @param int $code
     * @param Throwable|null $previous
     */
    public function __construct($sso, string $message = "", int $code = 0, Throwable $previous = null)
    {
        $this->sso = $sso;
        parent::__construct($message, $code, $previous);
    }

    public function render() {
        if ($this->sso instanceof Server) {
            return \response()->json([
                'code' => 'NotAttach',
                'message' => $this->getMessage(),
            ], static::$status);
        }
        if ($this->sso instanceof Client) {
            $params = ['return_url' => request()->fullUrl()];
            $url = $this->sso->getRequestUrl('attach', $params);
            if (request()->ajax()) {
                return \response()->json([
                    'code' => 'NotAttach',
                    'handle' => 'redirect',
                    'url' => $url,
                    'message' => $this->getMessage(),
                ], static::$status);
            }
            if (request('callback')) {
                return \response()->jsonp(request('callback'), [
                    'code' => 'NotAttach',
                    'handle' => 'redirect',
                    'url' => $url,
                    'message' => $this->getMessage(),
                ]);
            }
            return response()->redirectTo($url);
        }
        if (!env('APP_DEBUG')) {
            return response(view('errors.simple', ['message' => $this->getMessage()])->render(), static::$status);
        }
    }
}
